﻿#ifndef RS232_H
#define RS232_H

#include <QObject>
#include <QSerialPort>
#include <QDebug>
#include <QTimer>
#include "device.h"

class RS232 : public Device
{
    Q_OBJECT
public:
    explicit RS232(QObject *parent = nullptr);
    ~RS232();

    int nPort() const;
    void setNPort(int newNPort);
    int nBaud() const;
    void setNBaud(int newNBaud);
    int nCheck() const;
    void setNCheck(int newNCheck);
    int nDatabits() const;
    void setNDatabits(int newNDatabits);
    int nStopbits() const;
    void setNStopbits(int newNStopbits);

private:
    qint64 m_bytesToWrite = 0;

    void openSerialPort();
    void closeSerialPort();

public:
    virtual void writeData(const QByteArray &data) override;
    virtual void initDevice() override;

private slots:
    void readData();
    void handleError(QSerialPort::SerialPortError error);
    void handleBytesWritten(qint64 bytes);
    void handleWriteTimeout();

private:
    QSerialPort     *m_serial   = nullptr;
    QTimer          *m_timer    = nullptr;

public:
    virtual void writeXML(QXmlStreamWriter& writer) override;
    virtual void readFromXML(QXmlStreamReader& reader) override;
private:
    int         m_nPort;
    int         m_nBaud;
    int         m_nCheck;
    int         m_nDatabits;
    int         m_nStopbits;
};

#endif // RS232_H
